package com.jservice.api;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.log.Log;
import com.jservice.framework.dto.Setting;
import com.wondersgroup.upp.api.client.UPPlatformClient;
import com.wondersgroup.upp.api.client.impl.DefaultUPPlatformClient;
import com.wondersgroup.upp.api.core.UPPlatformRequest;
import com.wondersgroup.upp.api.core.UPPlatformResponse;

import java.io.IOException;

/**
 * UppClient
 *
 * @Author cwledit
 * @DATE 2017/6/13.
 */
public class UppClient {

    private static final Log LOG = Log.getLog(UppClient.class);

    private static UppClient uppClient;

    private static UPPlatformClient upPlatformClient;

    private UppClient() {
        upPlatformClient = new DefaultUPPlatformClient(Setting.getUppUrl(), Setting.getUppPrivateKey(), Setting.getUppPublicKey());
        upPlatformClient.setReadTimeout(15000);
    }

    /**
     * 获取公共的调用处理
     *
     * @return
     */
    public static UppClient getInstance() {
        if (uppClient == null) {
            // 同步块，线程安全的创建实例
            synchronized (UppClient.class) {
                // 再次检查实例是否存在，如果不存在才真正的创建实例
                if (uppClient == null) {
                    uppClient = new UppClient();

                }
            }
        }
        return uppClient;
    }

    public JSONObject doRequest(UPPlatformRequest request) throws IOException {
        LOG.debug(JSONObject.toJSONString(request,true));
        UPPlatformResponse response = upPlatformClient.invoke(request);
        LOG.debug(JSONObject.toJSONString(response,true));
        JSONObject result = new JSONObject();
        if ("000000".equals(response.getCode())) {
            if ("success".equalsIgnoreCase(response.getSub_code())){
                result = JSONObject.parseObject(response.getBiz_content());
                if(result == null){
                    result = new JSONObject();
                    result.put("code","999999");
                    result.put("msg","返回的 BIZ_CONTENT 为空或JSON格式错误!");
                    return result;
                }
                result.put("code",response.getCode());
                return result;
            }else{
                result.put("code", response.getSub_code());
                result.put("msg", response.getSub_msg());
                return result;
            }
        } else {
            result.put("code", response.getCode());
            result.put("msg", response.getMsg());
            return result;
        }
    }


}
